package com.hqyj.lyf.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hqyj.lyf.mapper.UserMapper;
import com.hqyj.lyf.pojo.Role;
import com.hqyj.lyf.pojo.User;
import com.hqyj.lyf.utils.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.security.auth.login.AccountNotFoundException;
import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取到当前登录用户的数据，通过认证方法存入shiro中的session取出来即可
        User loginUser = (User) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
        // 获取当前登录用户的角色信息，并存入一个set集合
        Set<String> roleSet = new HashSet<>();
        Role role = loginUser.getRole();
        if (role != null){
            roleSet.add(role.getRoleName());
        }else {
            //如果当前用户没有角色，默认按照用户处理*
            roleSet.add("用户");
        }
        // 创建AuthorizationInfo对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 把角色信息存入info对象中
        info.addRoles(roleSet);
        return info;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取当前的用户名
        String username = (String)token.getPrincipal();
        // 把当前登录用户名作为参数查询数据库
        User loginUser = userMapper.selectLoginInfo(username);
        // 判断登录的用户是否存在
        if (loginUser == null){
            // 不存在就抛出用户找不到异常
            throw new UnknownAccountException();
        }
        //成功登录
        //把当前用户信息存入到shiro中的session中
        SecurityUtils.getSubject().getSession().setAttribute("loginUser",loginUser);
        //获取盐
        ByteSource salt = ByteSource.Util.bytes(loginUser.getUsername());
        //返回认证对象，参数：用户名，密码，盐，getName方法
        return new SimpleAuthenticationInfo(loginUser.getUsername(),loginUser.getPassword(),salt,getName());
    }
}
